package com.jfire.json.serializer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.jfire.baseutil.collection.ObjectCollect;
import com.jfire.baseutil.collection.StringCache;
import com.jfire.json.JsonObject;
import com.jfire.json.field.JsonField;
import com.jfire.json.util.JsonConfig;
import com.jfire.json.util.JsonSerializer;

public class JsonObjectSerializer implements JsonSerializer
{
    
    @Override
    public Object transToJsonvalue(Object src, ObjectCollect collect)
    {
        return src;
    }
    
    @Override
    public void setJsonFields(JsonField[] jsonFields)
    {
        // TODO Auto-generated method stub
        
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void writeToString(StringCache cache, Object value, ObjectCollect collect)
    {
        Set<Entry> set = ((Map) value).entrySet();
        cache.append('{', set.size() * 2 + 1);
        for (Entry<String, Object> each : set)
        {
            if (each.getKey() != null && each.getValue() != null)
            {
                cache.append('"').append(each.getKey()).append('"');
                cache.append(':');
                JsonConfig.getSerializer(each.getValue().getClass()).writeToString(cache, each.getValue(), collect);
                cache.append(',');
            }
        }
        if (cache.isCommaLast())
        {
            cache.deleteLast();
        }
        cache.append('}');
    }
    
    @Override
    public Object toBean(Object value, Type type)
    {
        if (type.equals(JsonObject.class))
        {
            return value;
        }
        else
        {
            return JsonConfig.getSerializer((Class<?>)((ParameterizedType) type).getRawType()).toBean(value, type);
        }
    }
    
}
